﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace DataGridViewDemo
{
    public partial class Form1 : Form
    {
        private static string imagePath = AppDomain.CurrentDomain.BaseDirectory.Substring(0, AppDomain.CurrentDomain.BaseDirectory.IndexOf("bin")) + "Images\\";//列表图片路径
        public Form1()
        {
            InitializeComponent();
            InitControlsProperties();
        }

        private void InitControlsProperties()
        {
            this.dataGridView1.AutoGenerateColumns = false;
            TextAndImageColumn ColumnRoleID = new TextAndImageColumn();
            ColumnRoleID.DataPropertyName = "RoleID";
            ColumnRoleID.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
            ColumnRoleID.Name = "RoleID";
            ColumnRoleID.HeaderText = "权限ID";
            ColumnRoleID.Width = 200;
            this.dataGridView1.Columns.Add(ColumnRoleID);

            this.dataGridView1.AutoGenerateColumns = false;
            TextAndImageColumn ColumnRoleName = new TextAndImageColumn();
            ColumnRoleName.DataPropertyName = "RoleName";
            ColumnRoleName.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
            ColumnRoleName.Name = "RoleName";
            ColumnRoleName.HeaderText = "权限名称";
            ColumnRoleName.Width = 100;
            this.dataGridView1.Columns.Add(ColumnRoleName);

            this.dataGridView1.AutoGenerateColumns = false;
            TextAndImageColumn ColumnDescription = new TextAndImageColumn();
            ColumnDescription.DataPropertyName = "Description";
            ColumnDescription.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
            ColumnDescription.Name = "Description";
            ColumnDescription.HeaderText = "描述";
            ColumnDescription.Width = 150;
            this.dataGridView1.Columns.Add(ColumnDescription);
            dataGridView1.Rows.Add("Row 1", "Data 1", "DataGridView中同一个Cell中显示图片和文字");
            dataGridView1.Rows.Add("Row 2", "Data 3", "DataGridView中同一个Cell中显示图片和文字DataGridView中同一个Cell中显示图片和文字 ▼");
            dataGridView1.Rows.Add("Row 3", "Data 4", imagePath);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //string strConn = "Data Source=XIAN-PC;Initial Catalog=ReportServer;Persist Security Info=True;User ID=sa;Password=sa";
            //SqlConnection conn = new SqlConnection(strConn);
            //string strSql = "select * from Roles";
            //SqlCommand cmd = new SqlCommand(strSql, conn);
            //SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            //DataSet ds = new DataSet();
            //conn.Open();
            //adapter.Fill(ds, "Roles");
            //conn.Close();
            //this.dataGridView1.DataSource = ds.Tables["Roles"];
            // 添加一些示例数据  
       
        }

        private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            #region 第二列
            if (e.ColumnIndex == 1)
            {
                TextAndImageCell cell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex] as TextAndImageCell;
                if (cell != null && e.Value != null)
                {
                    try
                    {
                        string ajzt = cell.Value.ToString();
                        string path = imagePath;
                        switch (ajzt)
                        {
                            case "发布者":
                                path += "1.png";
                                break;
                            case "浏览者":
                                path += "2.png";
                                break;
                            default:
                                path += "3.png";
                                break;
                        }
                        cell.Image = GetImage(path);
                    }
                    catch (Exception ex)
                    {

                    }
                }
            }
            #endregion
        }


        private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            #region 第二列
            if (e.RowIndex >= 0 && e.ColumnIndex >=0)
            {
                TextAndImageCell cell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex] as TextAndImageCell;
                if (cell != null && e.Value != null)
                {
                    string strFileName = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString(); 
              


                    Image image = Image.FromFile(imagePath + (e.ColumnIndex ==2?"modify3.png":"1.png"));
                    //定义显示图片的矩形
                    Rectangle newRect = new Rectangle(e.CellBounds.X + e.CellBounds.Width - image.Width - 6, e.CellBounds.Y + 2, e.CellBounds.Height - 6,
                        e.CellBounds.Height - 6);

                    using (Brush gridBrush = new SolidBrush(this.dataGridView1.GridColor))
                    {
                        using (Pen gridLinePen = new Pen(gridBrush, 2))
                        {
                            Font newFont = new Font("宋体", 9, FontStyle.Regular);
                            // 计算文本尺寸  
                            // 注意：这里不使用 e.Graphics.MeasureString，因为它返回的是GDI+的浮点数尺寸  
                            Size proposedSize = TextRenderer.MeasureText(strFileName, newFont);

                            // 确定文本绘制的区域（考虑到图片占用的空间）  
                            RectangleF textRect = new RectangleF(e.CellBounds.Left + 0 + newRect.Width, e.CellBounds.Top + 5, e.CellBounds.Width - newRect.Width - 0, e.CellBounds.Height);

                            // 如果文本太长，则截断并添加省略号  
                            if (proposedSize.Width > textRect.Width)
                            {
                                // 尝试逐步缩短字符串，直到它适合或变得非常短  
                                StringBuilder sb = new StringBuilder(strFileName);
                                int fontwidth = TextRenderer.MeasureText(sb.ToString() + "...", newFont).Width;
                                while (fontwidth > textRect.Width)
                                {
                                    // 移除最后一个字符，直到合适为止  
                                    if (sb.Length > 0)
                                    {
                                        sb.Length--; // 移除最后一个字符  
                                        fontwidth = TextRenderer.MeasureText(sb.ToString() + "...", newFont).Width;
                                    }
                                    else
                                    {
                                        // 如果字符串已经为空但仍然太长（这通常不会发生，但以防万一）  
                                        break;
                                    }
                                }

                                // 添加省略号并确保至少有足够的空间来显示它  
                                if (sb.Length > 0 && fontwidth <= textRect.Width)
                                {
                                    strFileName = sb.ToString() + "...";
                                }
                                else
                                {
                                    // 如果连"..."都放不下，则可能只显示"..."或截取到能显示的最后一个完整字符  
                                    strFileName = "..."; // 或者实现更复杂的逻辑来找到能显示的最后一个完整单词或字符  
                                }
                            }
                            using (Brush backColorBrush = new SolidBrush(e.CellStyle.BackColor))
                            {
                                e.Graphics.FillRectangle(backColorBrush, e.CellBounds);

                                Point p1 = new Point(e.CellBounds.Left + e.CellBounds.Width, e.CellBounds.Top);
                                Point p2 = new Point(e.CellBounds.Left + e.CellBounds.Width, e.CellBounds.Top + e.CellBounds.Height);
                                Point p3 = new Point(e.CellBounds.Left, e.CellBounds.Top + e.CellBounds.Height);
                                Point[] ps = new Point[] { p1, p2, p3 };
                                e.Graphics.DrawLines(gridLinePen, ps);

                                e.Graphics.DrawImage(image, newRect);
                                e.Graphics.DrawString(strFileName.ToString(), newFont, Brushes.Black, e.CellBounds.Left + 0, e.CellBounds.Top + 5, StringFormat.GenericDefault);
                                //e.Paint(e.ClipBounds, DataGridViewPaintParts.All);
                                e.Handled = true;
                            }
                        }
                    }
                }
            }
            #endregion
        }

        public System.Drawing.Image GetImage(string path)
        {
            return System.Drawing.Image.FromFile(path);
        }
    }
}
